<template>
  <a-modal class="common-modal" :title="title" :footer="null" :width="1100" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading">
      <div class="p-20" style="height: calc(50vh + 78px)">
        <a-table rowKey="id" v-if="visible" :loading="loading" bordered size="small" :dataSource="dataSource" :columns="columns" :pagination="false" class="modal-table" :scroll="{y: '50vh'}" @change="handleTableChange">
          <template #bodyCell="{ column, record}">
            <template v-if="column.key === 'operate'">
              <span class="table-operate-container">
                <span v-if="record.hangParcelStatus">
                  <a-button @click="changeStatus(record, 0)" type="link" class="primary-link">{{ $t('common.cancel') }}</a-button>
                  <a-divider type="vertical" />
                  <a-button type="link" class="primary-link" @click="editPut(record)">{{ $t('other.modifiedShelving') }}</a-button>
                </span>
                <a-button v-else @click="changeStatus(record, 1)" type="link" class="primary-link">{{ $t('other.hitShelves') }}</a-button>
              </span>
            </template>
          </template>
        </a-table>
      </div>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{ $t('common.cancel') }}</a-button>
        <a-button @click="handleOk" v-if="dataSource.length" type="primary" class="confirm">{{ $t('common.ok') }}</a-button>
      </div>
    </a-spin>
    <EditPutawayModal ref="editPutawayModalRef" @ok="getList" />
  </a-modal>
</template>
<script setup>
import { ref } from 'vue'
import { roadmapColumns } from './prodTimeConfig'
import { filterObj } from '@/utils'
import axios from '@/utils/request'
import { message } from 'ant-design-vue'
import EditPutawayModal from './editPutawayModal'
import { cloneDeep, uniqBy } from 'lodash'
import i18n from '@/locales/index'
const { t } = i18n.global
let visible = ref(false)
let confirmLoading = ref(false)
let loading = ref(false)
let title = ref('')
let recordInfo = ref({})
let dataSource = ref([])
let couponInfo = ref(null) // 原始挂片中数据
let queryParam = ref({})
let stationId = ref(null)
let editPutawayModalRef = ref()
let columns = ref(roadmapColumns)
let isorter = ref({
  field: '',
  order: ''
})
const open = async (record) => {
  stationId.value = record.stationId
  await getList()
  title.value = `${t('hangManage.road')}${record.stationNo}`
  recordInfo.value = record
  visible.value = true
}
const getParams = () => {
  let params = []
  let dataList = []
  if (couponInfo.value) {
    let originInfo = dataSource.value.filter(i => i.id == couponInfo.value.id)[0]
    let nowCouponInfo = dataSource.value.filter(i => i.hangParcelStatus == 1 && i.id != couponInfo.value.id)
    dataList = nowCouponInfo.length ? [originInfo, nowCouponInfo[0]] : [originInfo]
  } else {
    dataList = dataSource.value.filter(i => i.hangParcelStatus == 1)
  }
  dataList.forEach(i => {
    params.push({
      lineNo: recordInfo.value.hangerLineNo,
      stationId: recordInfo.value.stationId,
      hangParcelStatus: i.hangParcelStatus,
      roadMapId: i.roadMapId,
      scheduleBillId: i.id
    })
  })
  return params
}
const handleOk = async () => {
  try {
    let params = getParams()
    confirmLoading.value = true
    let res = await axios.postAction('/api/hanger/hangerline-realtime/hang-parcel-putaway', params)
    confirmLoading.value = false
    if (res.success) {
      message.success(res.msg || t('common.doSuccess'))
      handleCancel()
    }
  } catch {
    confirmLoading.value = false
    console.log('err');
  }
}
const handleCancel = () => {
  couponInfo.value = null
  loading.value = false
  confirmLoading.value = false
  visible.value = false
  dataSource.value = []
  queryParam.value = {}
  isorter.value = {
    field: '',
    order: ''
  }
}
const getQueryParam = () => {
  let params = { ...queryParam.value }
  params.stationId = stationId.value
  params.sortingFields = isorter.value.field ? [isorter.value] : null
  return filterObj(params)
}
const getList = async () => {
  try {
    loading.value = true
    const res = await axios.postAction('/api/hanger/hangerline-realtime/get-online-schedulebill-by-station', getQueryParam())
    loading.value = false
    if (res.success && res.data) {
      dataSource.value = res.data
      let onHangList = dataSource.value.filter(i => i.hangParcelStatus == 1)
      couponInfo.value = onHangList.length > 0 ? { ...onHangList[0] } : null
      initColoum(res.data)
    }
  } catch {
    loading.value = false
    dataSource.value = []
  }
}
const initColoum = async (data) => {
  // 款号  款名  制单号 床号
  let columnsList = cloneDeep(columns.value)
  columnsList.forEach(i => {
    let filterList = ['moNo', 'styleNo', 'color', 'size', 'poNo', 'cutterNo', 'tailorBill']
    if (filterList.includes(i.dataIndex)) {
      let ary = data.map(el => ({ text: el[i.dataIndex], value: el[i.dataIndex] })).filter(el => el.value)
      i.filters = uniqBy(ary, 'value')
      i.onFilter = (value, record) => record[i.dataIndex] && record[i.dataIndex].indexOf(value) === 0
    }
  })
  columns.value = columnsList
}
const handleTableChange = (pagination, filters, sorter) => {
  if (Object.keys(sorter).length > 0) {
    isorter.value.field = sorter.field || ''
    isorter.value.order = sorter.order ? sorter.order == 'ascend' ? 'asc' : 'desc' : ''
  }
  getList()
}
const changeStatus = (record, status) => {
  if (status) {
    record.hangParcelStatus = status
    dataSource.value.forEach(i => {
      if (i.id != record.id) i.hangParcelStatus = 0
    })
  } else {
    record.hangParcelStatus = status
  }
}
const editPut = (record) => {
  editPutawayModalRef.value.open(record, recordInfo.value)
}
defineExpose({
  open
})
</script>
